<template>
  <div class="MaintenanceWorker-content">
    <el-table
      :data="searchData"
      style="width: 100%"
      :default-sort = "{prop: 'date', order: 'descending'}"
      >
      <el-table-column
        prop="repairnum"
        label="编号"
        sortable
        width="180">
      </el-table-column>
      <el-table-column
        prop="repairarea"
        label="区域"
        sortable
        width="180">
        <template slot-scope="scope">
          <span>
            {{idToNameFromList("area",scope.row.repairarea)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="repairtype"
        label="项目">
        <template slot-scope="scope">
          <span>
            {{idToNameFromList("type",scope.row.repairtype)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="repaircontent"
        label="内容">
        <template slot-scope="scope">
          <span style="white-space: pre-line;" v-html="scope.row.repaircontent"></span>
        </template>
      </el-table-column>
      <el-table-column
        prop="repairdate"
        label="报修时间"
        width="200px">
      </el-table-column>
      <el-table-column
        prop="repairprojectId"
        label="承修单位">
        <template slot-scope="scope">
          <span>
            {{idToNameFromList("unit",scope.row.repairprojectId)}}
          </span>
        </template>
      </el-table-column>
       <el-table-column
        prop="acceptuser"
        label="受理人">
         <template slot-scope="scope">
          <span>
            {{idToNameFromList("acceptuser",scope.row.acceptuser)}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="responsetime"
        label="受理用时"
         width="200px">
         <template slot-scope="scope">
           <span>
             {{responseTimeHandle(scope.row.repairdate,scope.row.responsetime)}}
           </span>
         </template>
      </el-table-column>
      <el-table-column
        prop="repairstate"
        label="状态">
        <template slot-scope="scope">
          <span>
            {{stateList[scope.row.repairstate]}}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
       width="100px">
        <template slot-scope="scope">
          <el-button v-if="role.isManager && scope.row.repairstate==1" type="primary" @click="acceptRepair(scope.row.repairnum)" style="width: 70px;height: 20px; font-size: 10px;text-align: center;line-height: 5px;" >受理</el-button>
          <el-button v-if="role.isManager && scope.row.repairstate==2" type="primary" @click="allocateRepairer(scope.row.repairnum,scope.row.repairarea)" style="width: 70px;height: 20px; font-size: 10px;text-align: center;line-height: 5px;" >分配维修工</el-button>
          <el-button v-if="(role.isManager
          || role.isRepairer)
          && (scope.row.repairstate != 4 && scope.row.repairstate != 5 && scope.row.repairstate !=6 )" type="primary" @click="reject(scope.row.repairnum)" style="width: 70px;height: 20px;margin: 0px;font-size: 10px;text-align: center;margin-top: 3px;line-height: 5px;">驳回</el-button>
          <el-button v-if="role.isRepairer
          && scope.row.repairstate == 3" type="primary" @click="repairerAccept(scope.row.repairnum)" style="width: 70px;height: 20px;margin: 0px;font-size: 10px;text-align: center;margin-top: 3px;line-height: 5px;">接单</el-button>
          <el-button v-if="role.isRepairer
          && scope.row.repairstate == 4" type="primary" @click="updateMaterial(scope.row.repairnum)" style="width: 70px;height: 20px;margin: 0px;font-size: 10px;text-align: center;margin-top: 3px;line-height: 5px;">提交材料</el-button>
          <el-button type="primary" @click="findDetail(scope.row.repairnum)" style="width: 70px;height: 20px;margin: 0px;font-size: 1px;text-align: center;margin-top: 3px;line-height: 5px;">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 驳回弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="rejectDialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>订单编号：{{repairNumSelect}}</span>
      <br/><br />
      <span>驳回理由:</span>
      <el-input v-model="rejectContent"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rejectDialogVisible = false;rejectContent=''">取 消</el-button>
        <el-button type="primary" @click="rejectSubmit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配人员弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="allocateDialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>订单编号：{{repairNumSelect}}</span>
      <br/><br />
      <span>分配策略:</span>
        <el-select v-model="allocatedStrategySelect" placeholder="请选择分配策略">
          <el-option
            v-for="item in allocatedStrategy"
            :key="item.value"
            :label="item.name"
            :value="item.value">
          </el-option>
        </el-select>
        <br />
      <span>选择维修工:</span>
          <el-select v-model="allocatedRepairerSelect" placeholder="请选择维修工">
            <el-option
              v-for="item in allocatedRepairer"
              :key="item.id"
              :label="item.accountName"
              :value="item.id">
          </el-option>
        </el-select>
        <br />
      <span>操作备注:</span>
      <el-input v-model="allocatedContent"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocateDialogVisible = false;allocatedStrategySelect=''">取 消</el-button>
        <el-button type="primary" @click="allocatedSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 材料提交弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="materialDialogVisible"
      :before-close="handleClose"
      width="70%">
      <span>订单编号：{{repairNumSelect}}</span>
      <br/><br />
      <el-form :model="uploadmaterialList" ref="uploadmaterialList" :rules="rules">
        <el-form-item label="材料1" prop="first">
          <el-col :span="8">
            <el-select v-model="uploadmaterialList.first.ditname" @change="getUnitByMaterialName(uploadmaterialList.first.ditname,0)">
                  <el-option
                    v-for="(item,index) in materialList"
                    :key="index"
                    :label="item"
                    :value="item">
                  </el-option>
            </el-select>
          </el-col>
          <el-col :span="8">
          <el-select  v-model="uploadmaterialList.first.ditcode">
                <el-option
                  v-for="item in materialUnitList[0]"
                  :key="item.dictcode"
                  :label="item.meteringunit"
                  :value="item.dictcode">
                </el-option>
          </el-select>
          </el-col>
          <el-col :span="5">
            <el-input-number size="small" v-model="uploadmaterialList.first.count" @change="handleChange" :min="1" :max="10" label="商品个数"></el-input-number>
          </el-col>
        </el-form-item>
        <el-form-item v-for="(item,index) in uploadmaterialList.adds"
        :label="'材料'+(index+2)"
        :key="index"
        :prop="'adds.'+index">
            <el-col :span="8">
              <el-select v-model="item.ditname" @change="getUnitByMaterialName(item.ditname,index)">
                    <el-option
                      v-for="(item,index) in materialList"
                      :key="'a'+index"
                      :label="item"
                      :value="item">
                    </el-option>
              </el-select>
            </el-col>
            <el-col :span="8">
            <el-select  v-model="item.ditcode">
                  <el-option
                    v-for="item in materialUnitList[index]"
                    :key="'b'+item.dictcode"
                    :label="item.meteringunit"
                    :value="item.dictcode">
                  </el-option>
            </el-select>
            </el-col>
            <el-col :span="5">
              <el-input-number size="small" v-model="item.count" @change="handleChange" :min="1" :max="10" label="描述文字"></el-input-number>
            </el-col>
        </el-form-item>
        <el-form-item prop="filePath">
          <el-upload action="http://localhost:8888/repairAttachment/upload" list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-success="success"
            :on-remove="handleRemove"
            :multiple="false"
            :limit="1">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="imgDialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="submitForm('uploadmaterialList')">提交</el-button>
      <el-button @click="addMaterial">新增材料</el-button>
      <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>

    </el-dialog>
  </div>
</template>

<script>
  export default{
    name:"Manager",
    props:["searchData","areaList","typeList","unitList","stateList","acceptuserList","role"],
    data(){
      return{
        rejectDialogVisible : false,
        allocateDialogVisible : false,
        materialDialogVisible : false,
        rejectContent :"",
        repairNumSelect:"",
        allocatedStrategy:[{name:"就近分配",value:"1"},{name:"全区调配",value:"2"}],
        allocatedStrategySelect:"",
        allocatedRepairer:[],
        allocatedRepairerSelect:"",
        areaSelect:"",
        allocatedContent:"",
        materialList:[],
        materialUnitList:[],
        uploadmaterialList: {
          adds:[],
          first:{ditcode:"",count:1,ditname:""},
          filePath:"",
          repairnum:""
        },
        dialogImageUrl:"",
        imgDialogVisible:false,
        // first:{ditcode:"",count:1,ditname:""},
        // filePath:"",
        // repairnum:""
        rules:{
          filePath:[{required:true,message:"图片不能为空",trigger:"blur', 'change'"}],
        }
      }
    },
    // inject:['reload'],
    methods:{
      allocateRepairer(repairNum,repairarea){
        this.areaSelect = repairarea
        this.repairNumSelect = repairNum
        this.allocateDialogVisible = true
      },
      findDetail(repairnum){
          this.$router.push({path: `/repair?repairnum=${repairnum}`,})
      },
      updateMaterial(repairnum){
        console.log(repairnum)
          this.repairNumSelect = repairnum
          this.uploadmaterialList.repairnum = repairnum
          this.getAllMaterial()
          this.materialDialogVisible = true
      },
      getUnitByMaterialName(name,index){
        this.$http.get("/housingMaterial/getMaterialByDictAllName",{
          params:{
            dictAllName:name,
            }
        }).then(resp=>{
          this.materialUnitList[index] = resp.data.data
          console.log(this.materialUnitList)
          this.$forceUpdate()
        })
      },
      jumpTo(route){
        this.$router.push(route)
      },
      acceptRepair(repairNumSelect){
        this.$http.post("/repairInfo/acceptRepair",{
          repairnum:repairNumSelect,
          repairstate:2,
          opername:"受理",
        }).then(resp=>{
          if(resp.data.code==200){
            location.reload()
            location.reload()
            alert("受理成功")
          }
          else{
            alert(resp.data.message)
          }
        })
      },
      reject(repairNum){
        this.rejectDialogVisible = true
        this.repairNumSelect = repairNum
      },
      rejectSubmit(){
        if(this.rejectContent==""){
          alert("驳回理由不能为空")
        }
        else{
          console.log(this.repairNumSelect)
          this.$http.post("/repairInfo/rejectRepair",{
            repairnum:this.repairNumSelect,
            repairstate:6,
            opername:"驳回",
            operreason:this.rejectContent,
          }).then(resp=>{
            console.log(resp.data.data)
            if(resp.data.code==200){
              location.reload()
              alert("驳回操作成功")
            }
            else{
              alert(resp.data.message)
            }
          })
          this.rejectDialogVisible = false
        }
      },
      allocatedSubmit(){
        this.$http.post("/repairInfo/allocateRepair",{
          repairnum:this.repairNumSelect,
          repairstate:3,
          opername:"分配维修工",
          operreason:this.allocatedStrategySelect,
          opercontent:this.allocatedContent,
          repairpersonid:this.allocatedRepairerSelect
        }).then(resp=>{
          if(resp.data.code==200){
            this.operreason = ""
            this.opercontent = ""
            location.reload()
            alert("分配操作成功")
          }
          else{
            alert(resp.data.message)
          }
        })
        this.allocateDialogVisible = false
      },
      //维修工接单
      repairerAccept(repairNum){
        this.$http.post("/repairInfo/repairerAccept",{
          repairnum:repairNum,
          repairstate:4,
          opername:"维修工接单",
        }).then(resp=>{
          if(resp.data.code==200){
            location.reload()
            alert("接单成功")
          }
          else{
            alert(resp.data.message)
          }
        })
      },
      test(){
        console.log(this.materialUnitList[0])
      },
      idToNameFromList(listName,id){
        if(listName=="area"){
          for(var i in this.areaList){
            if(id==this.areaList[i].id){return this.areaList[i].areaName}
          }
        }
        else if(listName=="unit"){
          for(var i in this.unitList){
            if(id==this.unitList[i].id){return this.unitList[i].unitName}
          }
        }
        else if(listName=="type"){
          for(var i in this.typeList){
            if(id==this.typeList[i].id){return this.typeList[i].projectName}
          }
        }
        else if(listName=="acceptuser"){
          for(var i in this.acceptuserList){
            if(id==this.acceptuserList[i].id){return this.acceptuserList[i].accountName}
          }
        }
      },
      //文件上传
      handleRemove(file, fileList) {
         this.uploadmaterialList.filePath = ""
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.imgDialogVisible = true;
      },
      success(response, file, fileList) {
        console.log(response)
        this.uploadmaterialList.filePath = response.data
        console.log(this.uploadmaterialList.filePath)
      },

      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
          done();
        })
        .catch(_ => {});
      },
      handleChange(value) {
        console.log(value);
      },
      submitForm(formname) {
        console.log(this.uploadmaterialList)
        var boolc = true
        //检查是否有重复
        var checkMap={}
        checkMap[this.uploadmaterialList.first.ditcode] = 1
        for(var i=0;i<this.uploadmaterialList.adds.length;i++){
          if(checkMap[this.uploadmaterialList.adds[i].ditcode]==1){
            alert("重复材料")
            boolc = false
          }
          else if(this.uploadmaterialList.adds[i].ditcode=="" || this.uploadmaterialList.adds[i].ditname==""){
            alert("空材料")
            boolc = false
          }
        }
        this.$refs[formname].validate((valid)=> {
          if (valid){
            if(boolc){
              console.log(this.uploadmaterialList)
              this.$http.post("/repairMaterial/addMaterial",this.uploadmaterialList).then(resp=>{
                if(resp.data.code==200){
                  location.reload()
                }
                else{
                  alert("异常，提交失败")
                }
              }).then(resp=>{
                if(boolc){
                  this.$http.post("/repairInfo/allocateRepair",{
                        repairnum:this.repairNumSelect,
                        repairstate:5,
                        opername:"维修完成"
                  }).then(resp=>{
                    if(resp.data.code==200){
                      location.reload()
                      alert("操作成功")
                      this.materialDialogVisible=false
                    }
                    else{
                      alert(resp.data.message)
                    }
                  })
                }
              })
            }
          }
            else{
              alert("参数校验失败")
            }
          })
      },
      resetForm(formName) {
        // this.$refs[formName].resetFields();
        this.materialUnitList = [],
        this.uploadmaterialList = {
          adds:[],
          first:{ditcode:"",count:1,ditname:""}
        }
        this.$forceUpdate()
      },
      removeDomain(item) {
        // var index = this.dynamicValidateForm.domains.indexOf(item)
        // if (index !== -1) {
        //   this.dynamicValidateForm.domains.splice(index, 1)
        // }
      },
      addMaterial() {
        this.uploadmaterialList.adds.push({ditcode:'',count:1,ditname:''})
      },
      // dynamicValidateForm: [{
      //   props:{
      //     dictallname:'',
      //     meteringnum: '',
      //     meteringunit:'',
      //     }
      // }]
      getAllMaterial(){
        this.$http.get("/housingMaterial/getAllMaterialName").then(resp=>{
            this.materialList = resp.data.data
            console.log(this.materialList)
            this.materialDialogVisible = true
        })
      },
      responseTimeHandle(startTime,endTime){
        if(endTime=="" || endTime == null){
          return endTime
        }
          var st = new Date(startTime.replace(/-/g,"/"));
          var et = new Date(endTime.replace(/-/g,"/"));
          var miss = et.getTime()-st.getTime()
          var hour =  Math.floor(miss/(3600*1000))
          var min = Math.ceil((miss - hour *(3600*1000))/(60*1000))
          return hour + "小时" + min +"分"
      }
    },
    create(){
    },
    watch:{
      allocatedStrategySelect(){
        //就近分配（本区）
        if(this.allocatedStrategySelect==1){
          this.$http.get("/userProjectArea/getRepairerByAreaId",{
            params:{
              id :this.areaSelect
            }
          }).then(resp=>{
            console.log(resp.data.data)
            this.allocatedRepairerSelect = ""
            this.allocatedRepairer = resp.data.data
          })
        }
        //全区调配
        else if(this.allocatedStrategySelect==2){
          this.$http.get("/account/getAllRepairer").then(resp=>{
            this.allocatedRepairerSelect = ""
            this.allocatedRepairer = resp.data.data
          })
        }
        else{
          console.log("q")
        }
      }
    }
  }
</script>

<style>
</style>
